var app = new Vue({
	el:"#app",
	data:function() {
		const initForm = {
                id: '',
                name: '',
                remark: '',
                fileId: '',
                cost: '',
                price: '',
                weight: '',
                profit: '',
                volumeWeight: '',
                detail: {
                    length: '',
                    width: '',
                    height: '',
                    color: '',
                    purchaseLink: '',
                    consultLink: ''
                },
                status: '1',
                suppliers: []
            }
        ;
		return {
            data2: [],
            value2: [],
			title:"Hello Vue",
			tableData:null,
			currentPage:1,
			pageSize:20,
			total:0,
			tableHeight:(document.documentElement.clientHeight-110),
			contextPath:"",
			showList:true,
			dialogTableVisible:false,
			dialogTitle:'新增',
			fields:[
				{
					prop:"name",
					label:"产品名称"
				},
				{
					prop:"remark",
					label:"备注"
				},
				{
					prop:"filePath",
					label:"缩略图"
				},
				{
					prop:"cost",
					label:"成本"
				},
				{
					prop:"price",
					label:"价格"
				},
                {
                    prop:"profit",
                    label:"利润"
                },
                {
                    prop:"cost",
                    label:"weight"
                },
                {
                    prop:"volumeWeight",
                    label:"体积重"
                },
				{
					prop:"status",
					label:"产品状态"
				},
			],
			form: initForm,
			initForm:initForm,
            rules:{
                name:[
					{
                        required:true,message:'请输入产品名称',trigger:'blur'
					}
				],
                detail:{
                	length:[
						{
                            required:true,message:'请输入产品长',trigger:'blur'
						}
					],
                    width:[
                        {
                            required:true,message:'请输入产品宽',trigger:'blur'
                        }
                    ],
                    height:[
                        {
                            required:true,message:'请输入产品高',trigger:'blur'
                        }
                    ],
				},
                weight:[
					{
                        required:true,message:'请输入产品重量',trigger:'blur'
					}
				],
                cost:[
                    {
                        required:true,message:'请输入产品成本',trigger:'blur'
                    }
                ],
                price:[
                    {
                        required:true,message:'请输入产品定价',trigger:'blur'
                    }
                ],
			},
	        multipleSelection:[],
            imageUrl:'',	//缩略图的URL
            fileUploadAction:'',
            searchForm:{
				name:''
			},
			loading:true,
            formLoading:true
		}
	},
    computed: {
        volumeWeight:{
        	get:function() {
                return ((Number(this.form.detail.length)
                    *  Number(this.form.detail.width)
                    * Number(this.form.detail.height))/5000).toFixed(3);
			},
			set:function(newValue) {
        		this.form.volumeWeight = newValue;
			}
		},
        cprofit:{
        	get:function() {
                //体积重和重量的更大值
                const realWeight = this.form.weight > this.volumeWeight?this.form.weight:this.volumeWeight;
                //亚马逊收费
                const amazonLogisticsCost = this.form.detail.height >=1.7 ? 3.19 : 2.41;
                const profit = this.form.price - this.form.price * 0.15 - amazonLogisticsCost - this.form.cost /6.4 - (realWeight * 30) / 6.4;
                return ((profit/this.form.cost) * 100).toFixed(2);
			},
			set:function(newValue) {
        		this.form.profit = newValue;
			}
		}
	},
	methods:{
		handleCurrentChange:function(val) {
			this.currentPage = val;
			this.getList();
		},
		handleSizeChange:function(val) {
			this.pageSize = val;
			this.getList();
		},
		//新增数据
		addForm:function() {
            //显示弹出框
			this.dialogTableVisible = true;
            this.form = this.initForm;
            this.imageUrl = '';
            this.dialogTitle = "新增";
            this.formLoading = false;
            //this.resetForm();
		},
		//删除多条列表项
		deleteItems:function() {
			if (this.multipleSelection.length == 0) {
				this.$alert("至少选择一条记录", "提示",{
					type:"warning"
				});
			} else {
				let that = this;
				this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
					let ids = [];
					that.multipleSelection.forEach(function(item,index){
						ids.push(item.id);
					});
					axios.put(that.contextPath + "/inventory/product/batchDelete",{
						ids:JSON.stringify(ids)
					}).then(function(){
						that.$message({
							type: 'success',
							message: '删除成功',
							duration:'1000'
						});
					that.getList();
					}).catch(function(){
						that.$message({
							type: 'waring',
							message: '删除失败',
							duration:'1000'
						});
					});
		        }).catch(() => {
		          this.$message({
		            type: 'info',
		            message: '已取消删除',
		            duration:'1000'
		          });          
		        });
			}
		},
		//编辑数据
		editItem:function(row) {
			//显示弹出框
			this.dialogTableVisible = true;
            this.dialogTitle = "编辑";
            //重置选中的供货商列表
            this.form.suppliers = [];
            //this.resetForm();

			let that = this;
            axios.get(this.contextPath + "/inventory/product/" + row.id)
				.then(function(response){
					that.form = response.data;
					//增加判断产品明细为空，把detail赋值为null时，导致vue赋值报错
					if (that.form.detail == null) {
                        that.form.detail = that.initForm.detail;
					}
					//缩略图展示
                    if (that.form.fileId != null && that.form.fileId !='') {
                        that.imageUrl = that.contextPath + "/fileupload/" + that.form.fileId;
					} else {
                        that.imageUrl = '';
					}
					//重置供货商列表，使之符合前端展示的格式
					let newSuppliers = [];
					//供货商展示
					if (response.data.suppliers != null && response.data.suppliers.length > 0) {
                        response.data.suppliers.forEach(function(item,index){
                            newSuppliers.push(item.supplierId);
						});
					}
                    that.form.suppliers = newSuppliers;
                    that.formLoading = false;

				})
				.catch(function () {
					that.formLoading = false;
                });
		},
		//删除单条列表项
		deleteItem:function(id) {
			let that = this;
			this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
					axios.post(this.contextPath + "/inventory/product/delete",{
						"id":id
					}).then(function(response){
						that.$message({
							type: 'success',
							message: '删除成功!',
							duration:'1000'
						});
						that.getList();
					}).catch(function(){
						that.$message({
							type: 'warning',
							message: '删除失败，请重试',
							duration:'1000'
						});
					});
		        }).catch(() => {
		          this.$message({
		            type: 'info',
		            message: '已取消删除',
		            duration:'1000'
		          });          
		        });
		},
		//保存表单数据
		onSubmit:function() {
			let flag = false;
            this.$refs["form"].validate((valid) => {
            	if(valid) {
                    flag = true;
            		console.info("验证成功");
				} else {
                    flag = false;
				}
			});
            if (!flag) {
            	return false;
			}
			let that = this;
            that.form.volumeWeight = that.volumeWeight;
			that.form.profit = that.cprofit;
			//对供货商数据进行处理，使之符合后台的格式
			if (that.form.suppliers != null && that.form.suppliers.length > 0) {
                let newSuppliers = [];
				that.form.suppliers.forEach(function(item,index){
                    newSuppliers.push({
						"productId":that.form.id,
						"supplierId":item
					});
				});
                that.form.suppliers = newSuppliers;
			}
			axios.post(this.contextPath + "/inventory/product/save",this.form)
				.then(function(){
					that.$message({
					type: 'success',
					message: '保存成功!',
					duration:'1000'
				});
				that.dialogTableVisible = false;
				that.getList();
				that.resetForm();
				})
				.catch(function(){
					that.$message({
						type: 'warning',
						message: '保存失败!',
						duration:'1000'
					});
				});
		},
		//表单取消提交操作
		cancelForm:function() {
			this.dialogTableVisible = false;
		},
		//列表选中行发生改变时
		handleSelectionChange:function(val) {
			this.multipleSelection = val;
		},
		//根据当前页和大小获得分页列表数据
		getList:function() {
			let that = this;
			that.loading = true;
			axios.post(this.contextPath + "/inventory/product/list/" + this.currentPage + "/" + this.pageSize,{
				"name":that.searchForm.name
			})
				.then(function(response){
					that.total = response.data.total;
					that.tableData = response.data.records;
					that.loading = false;
				})
				.catch(function(){
					that.loading = false;
				});
		},
		//产品缩略图上传成功后的调用方法
        handleAvatarSuccess:function(res, file) {
			this.form.fileId = res;
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        //产品缩略图上传前的调用方法
        beforeAvatarUpload:function(file) {
            const isJPG = file.type === 'image/jpeg'; //限制图片格式
            const isLt3M = file.size / 1024 / 1024 <= 3; //限制图片大小
			if (!isJPG) {
                this.$message.error('产品缩略图格式不正确,请重新上传');
			}
			if (!isLt3M) {
                this.$message.error('产品缩略图大小不能超过3MB!');
			}
            return isJPG && isLt3M;
        },
        searchClick:function() {
			this.currentPage = 1;
            this.getList();
        },
		//重置表单
        resetForm:function () {
            this.$refs["form"].resetFields();
        }
	},
	mounted:function() {
		this.contextPath = this.$refs.contextPath.value;
		this.fileUploadAction = this.contextPath + "/fileupload/upload"
		this.getList();
        let that = this;
        //获得供货商列表
        axios.post(this.contextPath + "/inventory/supplier/list",{})
            .then(function(response){
                response.data.forEach(function(item,index){
                    that.data2.push({
                        key:item.id,
                        label:item.supplierNumber + "-" + item.supplierName
                    });
                });
            })
	}
});
